/*
 * Copyright (c) 2009, Servoy-stuff
 * 
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 * http://www.fsf.org/licensing/licenses/lgpl.txt
 */

package net.stuff.servoy.beans.calendar.wicket;

import org.apache.wicket.Component;
import org.apache.wicket.Response;
import org.apache.wicket.util.string.Strings;
import org.wicketstuff.calendar.markup.html.form.DatePicker;

/**
 * 
 * @author servoy-stuff
 * http://www.servoy-stuff.net/
 */
public class WicketDatePicker extends DatePicker {

	private static final long serialVersionUID = 1L;
	
	private Component parent;
	
	public WicketDatePicker(Component parent) {
		this.parent = parent;
	}
	
	public void onRendered(Component component) {

		Response response = component.getResponse();
	    response.write("</td><td style=\"margin: 0px; padding: 0px; width: 5px;\">&nbsp</td>");
	    response.write("<td style=\"margin: 0px; padding: 0px; width: 16px;");
	    if (isReadOnly()) {
	    	response.write("display: none");
	    }
	    response.write("\">");
	    response.write("<img style=\"");
	    response.write(getIconStyle());
	    response.write("\" id=\"");
	    response.write(getIconId());
	    response.write("\" src=\"");
	    CharSequence iconUrl = getIconUrl();
	    
	    response.write(Strings.escapeMarkup((iconUrl != null) ? iconUrl.toString() : ""));
	    response.write("\" onclick=\"displayCalendar(document.getElementById('");
	    response.write(component.getMarkupId());
	    response.write("'),'");
	    
	    String datePattern = getDatePattern().replaceAll("mm", "ii").toLowerCase();
	    datePattern = datePattern.replace('s', '0');
	    response.write(datePattern);
	    if (datePattern.indexOf("h") == -1) {
	    	response.write("',this,false,null,true)\"");
	    } else {
	    	response.write("',this,true,null,true)\"");
	    }
	    response.write(" />");
	    
	} 

	public boolean isEnabled(Component paramComponent) {
	    return parent.isEnabled();
	}
	
	public boolean isReadOnly() {
		return ((WicketDateChooser)parent).isReadOnly();
	}
}
